<!--未连接口时 自己写死的菜单 配置动态路由 -->
<template>
    <div class="loginSinglePage">
        <a-spin :spinning="loadingFlag">
            <div class="loginSingle">
                <div class="title flexStartCenter">
                    <Title>
                        <template slot="pageName"> 登录 </template>
                    </Title>
                </div>
                <div class="content">
                    <div style="position:relative;width: 800px;height: 580px;">
                        <div class="loginBg">
                            <div class="loginFormBox">
                                <a-tabs :activeKey="tabKey" @change="tabChange">
                                    <a-tab-pane key="1" tab="密码登录">
                                        <div style="
                      text-align: center;
                      color: #333;
                      font-size: 16px;
                      margin: 10px 0 20px;
                    ">
                                            {{ loginType ? "账号登录" : "IAM用户登录" }}
                                        </div>
                                        <LoginForm v-if="loginType" @submit="onSubmit" />
                                        <IamLogin v-else @submitIAM="onSubmitIAM" />
                                        <div style="text-align: center; color: #999; margin-top: 32px">
                                            其他登录方式：<span style="cursor: pointer" @click="changeLoginType">{{ loginType ?
                                                    "IAM用户登录" : "账号登录"
                                            }}</span>
                                        </div>
                                    </a-tab-pane>
                                    <a-tab-pane key="2" tab="短信登录">
                                        <MessageForm pageName="login" ref="childMessage"
                                            @validateSuccess="validateSuccess">
                                            <template slot="submit">
                                                <a-button type="primary" style="width: 100%; margin-bottom: 17px"
                                                    @click="messageSubmit">
                                                    登录
                                                </a-button>
                                            </template>
                                        </MessageForm>
                                    </a-tab-pane>
                                </a-tabs>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <puzzVcode :puzzVcodeObj="puzzVcodeObj" @yzSuccess="yzSuccess"></puzzVcode>
        </a-spin>
    </div>
</template>

<script>
import LoginForm from "./module/loginForm.vue";
import IamLogin from "./module/iamLogin.vue";
import MessageForm from "./module/shortmessageForm.vue";
import Title from "./module/title.vue";
import { message } from "ant-design-vue";
import { mapMutations } from "vuex";
import puzzVcode from "./module/puzz-vcode.vue";

import lazyRoute from '@/utils/menuLoad.js'
import XEUtils from 'xe-utils'
import { err404 } from '@/router/routerData.js'
import menus from './menu'

export default {
    name: "loginSingle",
    components: {
        LoginForm,
        MessageForm,
        Title,
        IamLogin,
        puzzVcode
    },
    data() {
        return {
            tabKey: "1",
            loadingFlag: false,
            authUrl: "",
            loginType: true,
            puzzVcodeObj: {
                isShow: false
            },
            errorCount: 0,
            yzSuccessFlag: false,
            loginFormData: "",
            menuData: menus
        };
    },
    created() {
        this.authUrl = this.$route.query.authUrl;
    },
    methods: {
        ...mapMutations(["addMenu"]),

        tabChange(val) {
            this.tabKey = val;
        },
        changeLoginType() {
            this.yzSuccessFlag = false;
            this.errorCount = 0;
            this.loginType = !this.loginType;
        },
        yzSuccess(val) {
            this.yzSuccessFlag = val;
            if (this.loginType) {
                this.toLogin(this.loginFormData);
            } else {
                this.toIamLogin(this.loginFormData);
            }
        },
        onSubmitIAM(val) {
            this.authLogin()
        },
        onSubmit(val) {
            this.authLogin()
        },
        toLogin(val) {
            this.loadingFlag = true;
            axios({
                method: "post",
                url: `/wafa/Auth/doLogin?clientId=IAM1&responseType=code&loginType=1`,
                params: val
            })
                .then(res => {
                    this.yzSuccessFlag = false;
                    let tokenInfo = res.data.data.tokenInfo;
                    localStorage.setItem("token", tokenInfo.token);
                    localStorage.setItem("tokenInfo-IAM", JSON.stringify(tokenInfo));
                    let userInfo = res.data.data.userInfo;
                    sessionStorage.setItem("userInfo", JSON.stringify(userInfo));

                    this.checkTokenFn();
                })
                .catch(err => {
                    this.loadingFlag = false;
                    this.yzSuccessFlag = false;
                    message.config({
                        top: `16px`,
                        duration: 2,
                        maxCount: 3
                    });
                    this.$message.destroy();
                    this.$message.error("用户名或密码错误");
                    this.errorCount++;
                });
        },
        toIamLogin(data) {
            this.loadingFlag = true;
            axios({
                method: "post",
                url: `/wafa/Auth/jsonLogin`,
                data: data
            })
                .then(res => {
                    this.yzSuccessFlag = false;
                    let tokenInfo = res.data.data.tokenInfo;
                    // console.log(tokenInfo);
                    localStorage.setItem("token", tokenInfo.token);
                    localStorage.setItem("tokenInfo-IAM", JSON.stringify(tokenInfo));
                    let userInfo = res.data.data.userInfo;
                    sessionStorage.setItem("userInfo", JSON.stringify(userInfo));

                    this.checkTokenFn();
                })
                .catch(err => {
                    this.loadingFlag = false;
                    this.yzSuccessFlag = false;
                    message.config({
                        top: `16px`,
                        duration: 2,
                        maxCount: 3
                    });
                    this.$message.destroy();
                    this.$message.error("用户名或密码错误");
                });
        },
        checkTokenFn() {
            checkToken({}).then(res => {
                // console.log(res);
                sessionStorage.setItem("userName", res.data.userInfo.userName);
                this.permissionMenu = res.data.menuTree;
                //vuex存左侧菜单数据
                this.addMenu(this.permissionMenu);

                // 处理数据，加到动态路由里，防止刷新丢失，main.js里也增加动态路由
                let routeData = JSON.parse(JSON.stringify(this.permissionMenu));
                routeData.forEach(item => {
                    item.component = item.path.substring(1);
                    let children = JSON.parse(JSON.stringify(item));
                    item.children.push(children);
                    item.component = "home";
                    item.key = item.path;
                    item.path = "/";
                });
                //main.js增加动态路由的数据
                sessionStorage.setItem("demicRoute", JSON.stringify(routeData));
                //递归，component字符串变为文件
                let data = this.filterTree(routeData);
                this.$store.commit('setRouterData', data)
                //增加动态路由
                this.$router.addRoutes(data);

                this.loadingFlag = false;

                this.$router.push({
                    path: "/rcManage/loanOrderCheck"
                });
            });
        },

        messageSubmit() {
            this.$refs.childMessage.messageSubmit();
        },
        validateSuccess(val) {
            // console.log(val);
        },

        //递归过滤树
        filterTree(treeArr) {
            function findItem(arr) {
                let res = arr.filter(item => {
                    if (item.children && item.children.length > 0) {
                        item.children = findItem(item.children)
                    }
                    item.component = lazyRoute(item.component)
                    return item
                })
                return res
            }
            return findItem(treeArr)
        },
        // 处理菜单
        authLogin() {
            let keys = []
            XEUtils.eachTree(this.menuData, item => {
                keys.push(item.key)
            })
            this.$store.commit('setMenuData', this.menuData)
            let routeData = JSON.parse(JSON.stringify(this.menuData))
            routeData.forEach(item => {
                if (item.component != 'BasicLayout') {
                    let children = JSON.parse(JSON.stringify(item))
                    item.children.push(children)
                    item.component = 'BasicLayout'
                    item.key = item.path
                    item.path = '/'

                }
            });

            let data = this.filterTree(routeData)
            this.$store.commit('setRouterData', data)
            this.$router.addRoutes([...data, err404])
            this.$router.push({ path: '/index' })
        }
    },
    mounted() { }
};
</script>

<style scoped>
.loginSingle {
    width: 100vw;
    height: 100vh;
}

.title {
    width: 100%;
    height: 60px;
}

.flexStartCenter {
    display: flex;
    align-items: center;
}

.flexBetweenCenter {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.content {
    width: 100%;
    /* background: #180d5b; */
    background: url("../../assets/financialProduct/login/loginbg.png") no-repeat;
    background-size: cover;
    position: relative;
    height: calc(100vh - 60px);
    overflow: auto;
    display: flex;
    justify-content: center;
    align-items: center;
}

.loginFormBox {
    top: 62px;
    right: 63px;
    position: absolute;
    background: #fff;
    width: 338px;
    /* height: 326px; */
    padding: 31px 36px 49px;
}

.loginFormBox>>>.ant-tabs-bar {
    border-bottom: none;
}

.loginFormBox>>>.ant-tabs-nav-wrap {
    margin-bottom: 15px;
}

.loginFormBox>>>.ant-tabs-nav {
    font-weight: 700;
    font-size: 16px;
    color: #333333;
}

.loginFormBox>>>.ant-tabs-nav .ant-tabs-tab-active {
    font-weight: 700;
    font-size: 16px;
}

.loginSinglePage>>>.ant-spin-nested-loading>div>.ant-spin {
    min-height: 100%;
}

.loginBg {
    width: 800px;
    height: 590px;
    overflow: auto;
    position: absolute;
    /* background: url("../../../assets/financialProduct/login/loginbg.png") no-repeat; */
    background-size: 100%;
}
</style>
